package com.tang.crm.aspect;

import com.tang.crm.annotation.RequirePermission;
import com.tang.crm.exceptions.AuthException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 对权限码进行操作
 * @author SHIRELY阳
 */
@Component
@Aspect
public class PermissionProxy {

    @Autowired
    private HttpSession session;

    @Around("@annotation(com.tang.crm.annotation.RequirePermission)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        // 得到当前登录用户拥有的权限 （session作用域）
        List<String> permissios = (List<String>)session.getAttribute("permissions");
        // 判断用户是否拥有权限
        if (permissios == null || permissios.size() < 1){
            // 抛出认证异常
            throw new AuthException();
        }
        // 得到对应的目标
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        // 得到方法上的注解
        RequirePermission requiredPermission = methodSignature.getMethod().getDeclaredAnnotation(RequirePermission.class);
        // 判断注解上对应的状态码
        if (!(permissios.contains(requiredPermission.code()))){
            throw new AuthException();
        }
        result = joinPoint.proceed();
        return result;
    }
}
